<template>
  <div class="padding">
    <!-- 头部区域 -->
    <div class="page-header">
      <div class="title-section">
        <h1 class="page-title">
          <span class="merchant-name"></span> 提现记录
        </h1>
        <router-link :to="'/distributor/commissions'" class="back-link">
          <i class="fas fa-arrow-left"></i> 返回佣金列表
        </router-link>
      </div>
      <div class="header-actions">
        <button class="btn-primary" @click="openProductModal">
          <i class="fas fa-plus"></i> 添加产品
        </button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search_box">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="grid-content ep-bg-purple" />
          <el-input v-model="queryInfo.goods_name" placeholder="搜索产品名称3" :prefix-icon="Search" size="large"
            @change="searchTable" />
        </el-col>

        <el-col :span="6">
          <Select v-model="queryInfo.goods_type" mode="api" labelKey="title" valueKey="id"
            apiUrl="api/admin/shopLabelAddAndEdit" @change="searchTable" />
        </el-col>

        <el-col :span="6">
          <Select v-model="queryInfo.status" :data="productStatus" @change="searchTable" />
        </el-col>

        <el-col :span="6">
          <div class="flex justify-end algin-center">
            <el-button type="info" :icon="RefreshRight" size="large" @click="resetTable">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表格区域 -->
    <div class="margin-top">
      <el-table ref="multipleTableRef" :data="listData" style="width: 100%">
        <el-table-column type="selection" width="55" />

        <el-table-column property="产品图片" label="产品图片" width="120">
          <template #default="scope">
            <div class="box">
              <el-image :src="scope.row.head_img[0]" />
            </div>
          </template>
        </el-table-column>

        <el-table-column property="goods_name" label="产品名称" width="120" />

        <el-table-column property="goods_money" label="原价">
          <template #default="scope">
            <div v-for="item in scope.row.prices" :key="item.id">
              <div class="flex align-center price_item">
                <div class="flex align-center">
                  <div class="price_name">{{ item.money_name }}</div>

                  <div class="margin-left-xs price_value">¥{{ item.money }}</div>
                </div>

                <div class="flex align-center margin-left-sm">
                  <el-icon @click="handleProductPrice(scope.row, 'edit', item)">
                    <Edit />
                  </el-icon>

                  <el-icon class="margin-left-xs" @click="handleGoodsPrice(scope.row, item)">
                    <Delete />
                  </el-icon>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- <el-table-column property="address" label="折扣价" show-overflow-tooltip /> -->

        <el-table-column property="address" label="分类">
          <template #default="scope">
            <el-tag class="ml-2" type="success">{{ scope.row.goods_type && scope.row.goods_type.type_name }}</el-tag>
          </template>
        </el-table-column>

        <!-- <el-table-column property="address" label="库存" /> -->

        <el-table-column property="buy_num" label="销量" />

        <el-table-column property="address" label="状态">
          <template #default="scope">
            <el-tag class="ml-2" type="success" v-if="scope.row.status == 1">上架</el-tag>
            <el-tag class="ml-2" type="info" v-else>下架</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300">
          <template #default="scope">
            <div class="flex align-center">
              <el-button size="small" @click="openProductModal(scope.row)">编辑</el-button>

              <span class="flex margin-left-xs">
                <el-button size="small" type="success" @click="handleGoodsStatus(scope.row, '1')"
                  v-if="scope.row.status == 0">上架</el-button>

                <el-button size="small" type="info" @click="handleGoodsStatus(scope.row, '0')" v-else>下架</el-button>
              </span>

              <el-button class="margin-left-xs" size="small" type="primary"
                @click="handleProductPrice(scope.row, 'add')">添加价格</el-button>

              <el-button class="margin-left-xs" size="small" type="danger"
                @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="margin-top">
      <Pagination :total="total" @change="changePage" />
    </div>

    <!-- 产品表单模态框 -->
    <!-- <ProductFormModal v-model:visible="productModalVisible" :productData="currentProduct" :isEdit="isEditMode"
      @submit="handleProductSubmit" /> -->
    <ProductFormModal ref="productFormModalRef" :productStatus="productStatus" @reload="searchTable" />

    <!-- 添加价格弹窗 -->
    <ProductPriceFormModal ref="productPriceFormModalRef" @reload="searchTable" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import Select from '@/components/admin/Select.vue'
import { useRoute } from 'vue-router'
import useTableHook from '@/hooks/useTableHook'
import { GoodsList, GoodsAdd, GoodsPriceAddAndEdit, GoodsEdit } from '@/api/index'
import { RefreshRight } from '@element-plus/icons-vue'
import ProductFormModal from '@/components/admin/merchants/ProductFormModal.vue'
import ProductPriceFormModal from '@/components/admin/merchants/ProductPriceFormModal.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Pagination from '@/components/admin/Pagination.vue'

const route = useRoute()

const merchantId = computed(() => route.params.merchantId as string)

// 商品上下架
const handleGoodsStatus = (record, status) => {
  let statusText = record.status == 1 ? '下架' : '上架'

  ElMessageBox.confirm(`确认${statusText}商品: ${record.goods_name}`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      let newVal = JSON.parse(JSON.stringify(record))

      newVal.status = status

      const res = await GoodsEdit(newVal)

      ElMessage({
        type: 'success',
        message: `${statusText}成功!`
      })

      searchTable()
    } catch (err) {
      ElMessage({
        type: 'error',
        message: `${statusText}失败!`,
      })
    }
  })
}

// 删除商品
const handleDelete = (record) => {
  ElMessageBox.confirm(`确认删除商品: ${record.goods_name}`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      const res = await GoodsList({
        id: record.id,
        method: 'delete'
      })

      ElMessage('商品删除成功!')

      searchTable()
    } catch (err) {
      ElMessage({
        message: '商品删除失败!',
        type: 'error'
      })
    }
  })
}

// 产品价格 - start
const productPriceFormModalRef = ref(null)

const handleProductPrice = (record, type, goodsPriceData = {}) => {
  goodsPriceData.goodsId = record.id

  productPriceFormModalRef.value?.open({
    params: {
      type,
      goodsPriceData
    }
  })
}

const handleGoodsPrice = (record, item) => {
  ElMessageBox.confirm(`确认删除${record.goods_name}(${item.money_name})的价格`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    try {
      const res = await GoodsPriceAddAndEdit({
        id: item.id,
        method: 'delete',
        goodsId: record.id
      })

      ElMessage('价格删除成功!')

      searchTable()
    } catch (err) {
      ElMessage({
        message: '价格删除失败!',
        type: 'error'
      })
    }
  })
}
// 产品价格 - end

// 产品表单模态框状态
const productModalVisible = ref(false)
const currentProduct = ref<any>({})
const isEditMode = ref(false)

// 产品操作处理函数
function handleEditProduct(product: any) {
  console.log('编辑产品:', product)

  // 设置当前编辑的产品
  currentProduct.value = { ...product }

  isEditMode.value = true

  productModalVisible.value = true
}

const handleProductSubmit = async (productData) => {
  try {
    let res;

    if (productData.id) {
      res = await GoodsEdit(productData)
    } else {
      res = await GoodsAdd(productData)
    }

    searchTable()

    // 关闭模态框
    productModalVisible.value = false
  } catch (err) {
    // 关闭模态框
    productModalVisible.value = false
    console.log('handleProductSubmit', err)
  }
}

// 打开添加产品模态框
const openAddProductModal = () => {
  currentProduct.value = {
    merchantId: merchantId.value,
  }
  isEditMode.value = false
  productModalVisible.value = true
}

// ---------------------
const merchantName = ref('商户名称') // 默认名称，后续会从API获取

const productStatus = [
  {
    label: '全部状态',
    value: ''
  },
  {
    label: '上架',
    value: 1
  },
  {
    label: '下架',
    value: 0
  }
]

const queryInfo = ref({
  page: 1,
  limit: 10,
  shopId: '',
  goods_name: '',
  goods_type: '',
  status: ''
})

// 产品表单弹框
const productFormModalRef = ref()

const openProductModal = (record) => {
  let goods_img = record.head_img && record.head_img[0]

  productFormModalRef.value.open({
    data: {
      ...record,
      goods_img: goods_img,
      shopId: merchantId.value
    }
  })
}

// 重置表格
const resetTable = () => {
  // queryInfo.value = {
  //   page: 1,
  //   limit: 10,
  //   goods_name: '',
  //   goods_type: '',
  //   status:
  // }

  queryInfo.value.page = 1
  queryInfo.value.goods_name = ''
  queryInfo.value.goods_type = ''
  queryInfo.value.status = ''

  searchTable()
}

onMounted(() => {
  queryInfo.value.shopId = merchantId

  initTable()
})

const {
  total,
  listData,
  searchTable,
  initTable,
  changePage,
} = useTableHook(queryInfo.value, GoodsList)
</script>

<style lang="scss" scoped>
/* 头部区域样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.title-section {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #2c3e50;
}

.merchant-name {
  color: #e74c3c;
}

.back-link {
  display: inline-flex;
  align-items: center;
  font-size: 14px;
  color: #7f8c8d;
  text-decoration: none;
  transition: color 0.3s;
  margin-top: 5px;
}

.back-link:hover {
  color: #e74c3c;
}

.back-link i {
  margin-right: 5px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.btn-primary {
  background-color: #e74c3c;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  font-weight: 600;
  transition: background-color 0.3s;
}

.btn-primary:hover {
  background-color: #c0392b;
}

.btn-primary i {
  margin-right: 5px;
}

.price_item {
  .price_name {
    width: 60px;
  }

  .price_value {
    width: 60px;
  }
}
</style>
